import * as Cesium from 'cesium'

export default class MeasureDistanceTool {
  private viewer: Cesium.Viewer
  private positions: Cesium.Cartesian3[]
  private polylineEntity: Cesium.Entity | null
  private labelEntity: Cesium.Entity | null
  private handler: Cesium.ScreenSpaceEventHandler
  private isMeasuring: boolean

  constructor(viewer: Cesium.Viewer) {
    this.viewer = viewer
    this.positions = []
    this.polylineEntity = null
    this.labelEntity = null
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.canvas)
    this.isMeasuring = false // 追踪是否正在测量
    this.clear()
    this.initHandlers()
  }

  // 初始化鼠标事件
  private initHandlers(): void {
    // 左键点击：设置起点 & 终点
    this.handler.setInputAction((clickEvent: Cesium.ScreenSpaceEventHandler.PositionedEvent) => {
      const cartesian = this.viewer.scene.pickPosition(clickEvent.position)
      if (!cartesian) return

      if (!this.isMeasuring) {
        // 开始新的测量
        this.positions = [cartesian]
        this.addPoint(cartesian)
        this.isMeasuring = true
      } else {
        // 终点
        this.positions.push(cartesian)
        this.addPoint(cartesian)
        this.isMeasuring = false // 停止测量

        // 确保线段和标签正确保留
        this.updateDistanceLabel()
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

    // 鼠标移动：动态绘制线段 & 显示距离
    this.handler.setInputAction((moveEvent: Cesium.ScreenSpaceEventHandler.MotionEvent) => {
      if (!this.isMeasuring || this.positions.length === 0) return

      const movePosition = this.viewer.scene.pickPosition(moveEvent.endPosition)
      if (!movePosition) return

      if (this.positions.length === 1) {
        this.positions.push(movePosition) // 添加第二个点
        this.addLine()
      } else {
        this.positions[1] = movePosition // 更新终点位置
      }
      this.updateDistanceLabel()
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
  }

  // 添加一个点
  private addPoint(position: Cesium.Cartesian3): void {
    this.viewer.entities.add({
      position: position,
      point: {
        pixelSize: 8,
        color: Cesium.Color.YELLOW,
        outlineColor: Cesium.Color.BLACK,
        outlineWidth: 2
      }
    })
  }

  // 绘制线段（动态更新）
  private addLine(): void {
    if (this.polylineEntity) {
      this.viewer.entities.remove(this.polylineEntity)
    }
    this.polylineEntity = this.viewer.entities.add({
      polyline: {
        positions: new Cesium.CallbackProperty(() => this.positions, false), // 让 Cesium 动态更新
        material: Cesium.Color.RED,
        width: 2
      }
    })
  }

  // 更新距离标签
  private updateDistanceLabel(): void {
    if (this.positions.length < 2) return

    const centerPoint = Cesium.Cartesian3.midpoint(
      this.positions[0],
      this.positions[1],
      new Cesium.Cartesian3()
    )
    const distance = Cesium.Cartesian3.distance(this.positions[0], this.positions[1])
    const distanceText = `距离: ${distance.toFixed(2)} m`

    if (this.labelEntity) {
      this.labelEntity.position = centerPoint
      this.labelEntity.label!.text = distanceText
    } else {
      this.labelEntity = this.viewer.entities.add({
        position: centerPoint,
        label: {
          text: distanceText,
          font: '16px sans-serif',
          fillColor: Cesium.Color.WHITE,
          showBackground: true,
          backgroundColor: Cesium.Color.BLACK.withAlpha(0.7),
          pixelOffset: new Cesium.Cartesian2(0, -20),
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM
        }
      })
    }
  }

  // 清除所有测量数据
  public clear(): void {
    if (this.polylineEntity) this.viewer.entities.remove(this.polylineEntity)
    if (this.labelEntity) this.viewer.entities.remove(this.labelEntity)
    this.positions = []
    this.polylineEntity = null
    this.labelEntity = null
    this.isMeasuring = false
  }
}
